/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SLE_TIMER_H
#define SLE_TIMER_H

#include <functional>
#include <mutex>
#include <future>
#include <list>

namespace OHOS {
namespace NearLink {
using namespace std::chrono;

#define MS_PER_SECOND 1000
#define NS_PER_MS 1000000

#ifndef CHECK_EXCEPT_INTR
#define CHECK_EXCEPT_INTR(fn) \
    do {                      \
    } while ((fn) == -1 && errno == EINTR)
#endif

class Timer;
class TimerManager {
public:
    static TimerManager &GetInstance();

    bool AddTimer(Timer &timer);
    void RemoveTimer(Timer &timer);

private:
    static const int MAXEPOLLEVENTS = 128;
    TimerManager();
    ~TimerManager();

    void Initialize(std::promise<int> startPromise);
    void OnTimer(std::promise<int> startPromise);
    void OnCallback(Timer &timer) const;

    int epollFd_ {-1};
    int stopFd_ {-1};
    std::mutex mutex_ {};
    std::list<Timer *> unregisteredList_ {};
    std::unique_ptr<std::thread> thread_ {};
};

class Timer {
public:
    Timer(const std::function<void()> &callback);
    ~Timer();

    bool Start(int ms, bool isPeriodic = false);
    bool Stop();

private:
    int fd_ {-1};
    std::mutex mutex_ {};
    std::function<void()> callback_ {};

    friend class TimerManager;
};
} // NearLink
} // OHOS

#endif // SLE_TIMER_H
